package com.xiashitech.agent.proxy.hutool.extload;

import cn.hutool.setting.Setting;
import com.xiashitech.agent.cache.classloader.ClassLoaderCache;
import com.xiashitech.agent.config.StartConfig;

import javax.sql.DataSource;

public class PooledDSFactory {

    private static String className = "cn.hutool.db.ds.pooled.PooledDSFactory";

    private Object pooledDSFactory;

    public static PooledDSFactory getInstance(Object setting) {
        try {
            Class pooledDSFactoryClass = ClassLoaderCache.getLaunchClassLoader().loadClass(className);
            PooledDSFactory pooledDSFactory = new PooledDSFactory();
            pooledDSFactory.pooledDSFactory = pooledDSFactoryClass.getDeclaredConstructor(Setting.class).newInstance(setting);
            return pooledDSFactory;
        } catch (Throwable e) {
            StartConfig.throwableStackPrinter(e);
        }
        return null;
    }

    public DataSource getDataSource() {
        try {
            if (pooledDSFactory == null) {
                return null;
            }
            Class pooledDSFactoryClass = ClassLoaderCache.getLaunchClassLoader().loadClass(className);
            return (DataSource)pooledDSFactoryClass.getMethod("getDataSource").invoke(pooledDSFactory);
        } catch (Throwable e) {
            StartConfig.throwableStackPrinter(e);
        }
        return null;
    }
}
